	const {convertdBm2RSSI,getBeforeDay,padZero} = require('@/utils/util.js');
	let constant = getApp().globalData.constant;
	let LOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4; //650设备 分主辅码流(截图按实际的分辨率来)
	let LOCK20 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK20; //博克乐鑫新UI派生PID 不分主辅码流
	let LOCK9 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK9; //XM650V200新版USB猫眼主PID（双摄）
	let LOCK22 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK22; // 乐鑫版本USB猫眼主PID(双目)
	export const liveMixins = {
		data() {
			return {
				list: {
					number: 98
				},
				// 设备对象
				device: {
					deviceName: ''
				},
				// 缓存列表
				deviceList: [],
				// 是否存在缓存
				isCache: false,
				//保活定时器
				timer: null,
				// 保活次数迭代变量
				keepAliveCount: 0,
				/** 推流相关 */
				// 视频对象
				videoContext: {},
				// 播放地址
				// url: 'https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20200317.mp4',
				url: '',
				// 高清还是标清（标清用: 1 表示， 高清用: 0 表示）
				stream: '1',
				// 高清还是标清文本说明
				streamText: '标清',
				// 高清还是标清icon
				streamTextIcon: 'FHD',
				//是否全屏
				isFullScreen: false,
				// 显示隐藏bar控条
				isShowBar: true,
				//加载中
				isLoading: true,
				//加载中文字说明
				loadingText: '正在获取视频播放地址...',
				//截图
				captureUrl: '',
				// 显示截图
				isCapture: false,
				// 时间间隔
				time: 3,
				/** 云服务 */
				isCloud: true,
				cloudText: '',
				//静音
				mutedIcon: 'https://statics.xmcsrv.net/weixin/soundoff2.png',
				wifiUrl: null,
				isMute: true,
				tempIsMute:false,
				isClose:false,
				talkIcon: 'https://statics.xmcsrv.net/weixin/talk0.png',
				temporaryIcon: 'https://statics.xmcsrv.net/weixin/linshiw.jpg',
				unlockIcon: "https://statics.xmcsrv.net/weixin/lock.png",
				isTalk: false,
				//
				screenHeigh: '',
				navBarHeight: '',
				clientHeight: '',
				isShowHD: false,
				hdText: '标清',
				hdList: [{
					label: '标清',
					id: '1'
				}, {
					label: '高清',
					id: '0'
				}],
				isHd: false,
				iconList: ['https://statics.xmcsrv.net/weixin/lock.png', 'https://statics.xmcsrv.net/weixin/talk.png',
					'https://statics.xmcsrv.net/weixin/lock.png'
				],
				// 'https://statics.xmcsrv.net/weixin/door-cloud2.png' 设备回放
				rightList:[
					{icon:'https://statics.xmcsrv.net/weixin/live/SD.png',id:'HD'},
					{icon:'https://statics.xmcsrv.net/weixin/capture.png',id:'capture'},
					{icon:'https://statics.xmcsrv.net/weixin/message.png',id:'msg',url:'./cloudMsg'},
					{icon:'https://statics.xmcsrv.net/weixin/soundoff2.png',id:'sound'},
					{icon:'https://statics.xmcsrv.net/weixin/door-setting.png',id:'setting',url:'./setting/setting'}
				],
				soundOnIcon:'https://statics.xmcsrv.net/weixin/soundon.png',
				soundOffIcon:'https://statics.xmcsrv.net/weixin/soundoff2.png',
				popupList: [{
						icon: 'https://statics.xmcsrv.net/weixin/card-video.png',
						title: '卡存录像',
						url: '/jvss/pagesDevice/device/device-live/door-lock/msgDetail'
					},
					{
						icon: 'https://statics.xmcsrv.net/weixin/cloud-video.png',
						title: '云存录像',
						url: '/jvss/pagesDevice/device/device-live/door-lock/msgDetail'
					},
					{
						icon: 'https://statics.xmcsrv.net/weixin/album.png',
						title: '卡存相册',
						url: '/jvss/pagesDevice/device/device-live/door-lock/album'
					},
				],
				show: false,
				talkStatus: false,
				password: '',
				focus: false,
				cacheMaxTime: 0.5,
				cacheMinTime: 0.1,
				isPush: false,
				pushVideoContext: {},
				talkUrl: '',
				isLoginSuccess: true,
				isLogin: false,
				navTitle: '',
				TailoredInfo: {},
				bl: null,
				bal: null,
				autoPause:true,
				liveTimer: null,
				liveState: false,
				count: 0,
				hideType:1,
				isShowPush:true,
				isShowPlayer:true,
				viewerNum:0,
				envVersion:'release',
				tryCount:0,
				tryTokenCount:0,
				tryTalkTokenCount:0,
				tryTalkOfflineCount:0,
				tryTalkWakeUpCount:0,
				tryTalkTokenErrCount:0,
				tryTalkUnnormalCount:0,
				isLogout:false,
				pictureMode:["push","pop"],
				isShowLock:true,
				netSpeed:'',//网速
				isShowPlayBtn:false,
				isStartPlay:false,
				isPlay:true,
				captureBottom:0,
				tryCaptureNum:0,
				deviceStatus:'',
				pathType:1,
				disConnectCount: 0,
				isShowDeepSleepModal:false,
				isShowLightSleepModal:false,
				isShowDelModal:false,
				LightSleepStatus:false,
				DeepSleepStatus:false,
				isFirstFrame:false,
				playType:0,
				pullTimer:null,
				scanvsWidth:217,//260,
				scanvsHeight:386,//462,
				canvasImgPath:'',
				phoneType: '',
				isShowBg:true,
				noDataStatus:false,
				isSupportSpeak:false,
				playOrNot:null,
				executeCallback:false,//是否执行mqtt消息回调避免重复执行
				talkStausIcon:{
					on:{
						'live-lexin':'https://statics.xmcsrv.net/weixin/talk1.png',
						'live-lexin2':'https://statics.xmcsrv.net/weixin/talk3-lexin.gif'
					},
					off:{
						'live-lexin':'https://statics.xmcsrv.net/weixin/talk0.png',
						'live-lexin2':'https://statics.xmcsrv.net/weixin/talk-lexin.png'
					}
				},
				pageKey:'',//每个预览页面的对讲图标根据这个值来获取
				lastClickTalkTimeStamp:0,
				clickTalkStatus:false,
				twoWayVideoUrl:'',//双向视频对讲地址
				isSupportVideoTalk:false,//是否支持双向视频对讲
				maxCameraNum:1,//大于1 就是多目摄像头
				currentCameraNum:1,//当前摄像头个数（可以通过配置关闭摄像头）
				switchType:0x00000001,//当前摄像头类型
				supportSwitchType:[], //支持的画面切换，数组顺序代表画面切换顺序 0x00000001摄像头1 0x00000002摄像头2 0x00000003摄像头1+摄像头2拼接
				isMicrophoneOn:true,//麦克风是否打开
				isSpeakerOn:false, //扬声器是否打开  是否静音
				volumeType:'voicecall',//media媒体音量 	voicecall通话音量
				isCameraOn:true,//手机镜头是否打开
				cameraPosition:'front',//front前置摄像头 back后置
				fps:12,//帧率，有效值为 1~30
				videoWidth:320,//上推的视频流的分辨率宽度
				videoHeight:576,//上推的视频流的分辨率高度
				audioCodePlayer:'g711a', //播放器音频编码:g711a/g711u 
				audioAccuracyPlayer:'',// 播放器音频精度
				videoPlayer:'h264',//播放器视频编码:h264/h265 
				audioKHZPlayer:'8000',//播放器音频采样率
				talkTime:0,
				talkTimerID:null,
				isOpenVideoTalk:false, //是否开启了双向对讲
				isStartCountDown:false,
				countDown:'00:00',//通话倒计时
				deviceTerminatedCallStatus:false,//设备端挂断双向对讲弹框提示
				pushTop:50,
				appletIdentify:getApp().globalData.appletIdentify,
				generalIdentify:getApp().globalData.generalIdentify,
				powerSavingMode:{},//省电模式
				douCamStat:0,// 0 : 单目状态; 1 : 双目状态; 
				pushVideoInfo: {
					videoBitrate: '',
					audioBitrate: '',
					videoFPS: '',
					videoGOP: '',
					netSpeed: '',
					videoWidth: '',
					videoHeight: '',
					videoCache: '',
					audioCache: '',
				},
				isGetVideoTalk:false,
                streamSwitch: false,				
				netstatus:{},
				livePlayCode:{},
				islivePlayLinkData:false,
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.getPhoneType()
			this.getClineHeight()
			this.screenHeigh = uni.getSystemInfoSync().windowHeight + 'px'
			let res = uni.getSystemInfoSync(); //系统信息
			this.navBarHeight = res.statusBarHeight + 44
			let enData = decodeURIComponent(options.device)
			this.device = JSON.parse(enData)
			this.playOrNot = options.playOrNot
			//清晰度
			let definition = uni.getStorageSync('definition')
			if(definition){
				if(definition.deviceNo == this.device.deviceNo){
					this.stream = definition.stream;
					this.rightList.forEach((z)=>{
						if(z.id == "HD"){
							if(definition.stream == 0){
								z.icon = 'https://statics.xmcsrv.net/weixin/live/HD.png'
								this.isHd = true
							}else{
								z.icon = 'https://statics.xmcsrv.net/weixin/live/SD.png'
								this.isHd = false
							}
						}
					})
				}
			}
			uni.setStorageSync('deviceToken',this.device.token)
			getApp().globalData.deviceToken = this.device.token
			this.getCurrentDevice(this.device);
			uni.setNavigationBarTitle({
				title: this.device.deviceName
			});
			this.navTitle = this.device.deviceName
			this.isShowLock = this.device.localUiKey == 'ui_doorbell'?false:true
			this.getTailoredConfig()
			// this.executeCallback = true
			// this.websocketInfo()
			uni.$on('onWebsocketMessage', this.getLiveMqttInfoCallback)
			if(this.playOrNot != 'suspend'){
				uni.showLoading({
					mask:true,
					title:'正在获取视频播放地址...'
				});
			}
			this.envVersion = ''
			//监听小程序退到后台
			let that = this
			uni.$on('appLogout',function(data){
				that.closeAllLinks(1)
				this.$logs({info: '小程序切换到后台-live',timer:getApp().globalData.keepTimer,data:data})
			})
			if (options.type) {
				this.pathType = options.type
			}
			//是否展示云存储图标
			if(this.device.xmcCssVid){
				if(this.device.xmcCssVid.support){
					this.rightList.forEach((item,index)=>{
						if(item.id == 'cloud'){
							item.icon = !this.device.xmcCssVid.enable?'https://statics.xmcsrv.net/weixin/door-cloud-disable.png':this.device.xmcCssVid.isExpire?'https://statics.xmcsrv.net/weixin/door-cloud.png':'https://statics.xmcsrv.net/weixin/door-cloud-expire.png'
						}
					})
				}else{
					this.rightList.forEach((item,index)=>{
						if(item.id == 'cloud'){
							this.rightList.splice(index,1)
						}
					})
				}
			}
		},
		onShow: function() {
			this.videoContext = uni.createLivePlayerContext('livePlayer')
			this.pushVideoContext = uni.createLivePusherContext('pushLive')
			this.autoPause = true
			this.isShowPush = true
			this.isShowPlayer = true
			if(this.playOrNot == 'suspend'){
				this.isShowPlayBtn = true
			}else{
				this.isShowPlayBtn = false
			}
			this.hideType = 1
			this.isLogout = false
			this.isFirstFrame = false
			if(this.device.pid == LOCK20){
				this.stream = '0'
			}
			this.getInit();
			// this.loginOrAuto()
			this.getDevicePropStatus('wifiSignal')
			this.getDevicePropStatus('batteryPower')
			this.getDeviceTypePropList()
			let time1 = this.getCurrentTime()
			this.$logs({info: '刚进播放页时间',time:time1})
			
			uni.$on('editDeviceName',(data)=>{
				if(data.sn == this.device.deviceNo){
					this.navTitle = data.deviceName
					this.device.deviceName = data.deviceName
				}
			})
		},
		onHide: function() {
			console.log('--- device-live:onHide:');
			this.autoPause = false
			this.closeAllLinks(this.hideType)
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			console.log('--- device-live:onUnload:',getApp().globalData.keepTimer);
			this.closeAllLinks(1)
			uni.$emit('deviceLogout', {
				isBack: true,
				deviceNo: this.device.deviceNo,
				token:this.device.token,
				localUiKey:this.device.localUiKey || ''
			})
			this.isLogout = true
			this.$logs({info: '退出预览页时保活定时器',data:getApp().globalData.keepTimer,isLogin:this.isLogin,isLogout:this.isLogout})
			uni.$emit('backCloudMsg', {
				isBack: true
			})
			// this.executeCallback = false
			uni.$off('onWebsocketMessage', this.getLiveMqttInfoCallback)
			clearInterval(this.talkTimerID)
		},
		onReady(){
			let info = uni.getSystemInfoSync()
			let pixelRatio = info.pixelRatio
			this.scanvsWidth = 720 / pixelRatio ;
			this.scanvsHeight = (1280/720)*this.scanvsWidth
			console.log('获取系统信息===',info);
			
			let pages = getCurrentPages()
			let currentPageRoute = pages[pages.length -1].route
			this.pageKey = currentPageRoute.split('/')[currentPageRoute.split('/').length-1]
		},
		watch:{
			talkTime(val){
				let second = 0
				let minute = 0
				let seconds = 0
				if(val == 180){
					this.isStartCountDown = true
					this.talkTimerID = setInterval(()=>{
						second ++
						minute = (Math.floor(second/60))<10?('0'+Math.floor(second/60)):Math.floor(second/60)
						seconds = (second%60)<10?('0'+second%60):second%60
						this.countDown = minute+':'+ seconds
						if(second == 180){
							// this.backAction()
							// clearInterval(this.talkTimerID)
						}
					},1000)
				}
			}
		},
		methods: {
			// 获取机型
			getPhoneType() {
				const sys = uni.getSystemInfoSync()
				console.log(sys, '机型')
				this.phoneType = sys.deviceModel.slice(0, 4)
				console.log(this.phoneType, '机型')
			},
			//画布画图
			async canvasDrawImage(img){
				await this.$refs.rCanvas.drawImage({
					url:img,
					x: 0,
					y: 0,
					w: this.scanvsWidth,
					h: this.scanvsHeight,
				}).catch(err_msg => {
					this.$logs({info:'canvas画图失败',err:err_msg})
				})
				// 生成海报
				await this.$refs.rCanvas.draw((res) => {
					this.canvasImgPath = res.tempFilePath
					// 保存图片
					this.$refs.rCanvas.saveImage(res.tempFilePath)
					uni.showToast({
						title: '保存相册成功',
						icon: "none"
					})
				})
			},
			getLiveMqttInfoCallback(res) {
				// getApp().globalData.mqtt.getMessage(res => {
					// let info = JSON.parse(res.data)
					// if(!this.executeCallback) return
					let info = JSON.parse(res)
					let page = getCurrentPages()
					if(info.sn == this.device.deviceNo){
						console.log('播放页接收数据', JSON.parse(res));
						info.props.forEach(item=>{
							if(item.propCode ==  "wifiSignal"){
								this.wifiUrl = convertdBm2RSSI(item.propValue,3)
							}
							if(item.propCode ==  "batteryPower"){
								this.bl = item.propValue
							}
							if(item.propCode == "remoteUnlock"){
								let flag = uni.getStorageSync('isCurrentUserUnlock')?uni.getStorageSync('isCurrentUserUnlock'):false
								if(flag){
									uni.showToast({
										title:'开锁成功',
										duration:2000,
										success: () => {
											setTimeout(()=>{
												this.backAction()
											},2000)
										}
									})
								}
								uni.setStorageSync('isCurrentUserUnlock',false)
								this.$logs({info:'远程开锁成功',item:item})
							}
							if(item.propCode == "remoteUnlockFailed"){
								// uni.showToast({
								// 	title:'开锁失败',
								// 	duration:2000,
								// })
								this.$logs({info:'远程开锁失败',item:item},'error')
							}
							if(item.propCode == "deviceTerminatedCall"){
								this.deviceTerminatedCallStatus = true
								setTimeout(()=>{
									this.backAction()
									this.deviceTerminatedCallStatus = false
								},1500)
								this.$logs({info:'双向对讲挂断电话',item:item})
							}
							//唤醒主控推送 "sleep/wake"
							if(item.propCode == "masterSleepState"){
								if(item.propValue == 'wake'){
									this.getdoorLocktability('MultiCamera')
									this.getdoorLocktability('DecoderPram')
								}
								//主控休眠
								if(item.propValue == 'sleep'){
									// this.onDeviceLightSleep()
								}
								this.$logs({info:'主控状态推送',item:item})
							}
							// DeepSleep深度休眠,LightSleep轻度休眠,WakeUp唤醒,PreSleep准备休眠
							if(item.propCode ==  "sleepState"){
								this.$logs({apiUrl: '乐鑫播放接收websocket数据',sn:info.sn,data:item,propValue: item.propValue})
								console.log('播放页接收数据设备状态', item.propValue);
								let millTime = info.timeStamp
								this.deviceStatus = item.propValue
								if(this.deviceStatus == 'DeepSleep'){
									uni.hideLoading()
									this.videoContext.stop();
									if(!this.isShowDeepSleepModal){
										if(page[page.length - 1].$page.fullPath.includes('live-lexin')){
											this.DeepSleepStatus = true
											this.isShowDeepSleepModal = true
										}
									}
								}
								if(this.deviceStatus == 'LightSleep'){
									this.onDeviceLightSleep()
								}
								if(this.deviceStatus == 'PreSleep'){
									if(page[page.length - 1].$page.fullPath.includes('live-lexin')){
										return uni.showToast({
											title:'准备休眠中',
											icon:'none'
										})
									}
								}
								// 锁板准备休眠中
								if(this.deviceStatus == 'MasterControlPreSleep'){
									
								}
								if(this.deviceStatus == 'WakeUp'){
								}
								if(this.deviceStatus == 'OffLine'){
								}
							}
						})
					}
				// })
			},
			//监听设备进入浅休眠状态时逻辑处理
			onDeviceLightSleep(){
				if(this.talkTimerID){
					clearInterval(this.talkTimerID)
					this.countDown = ''
				}
				let page = getCurrentPages()
				uni.hideLoading()
				this.isStartPlay = false
				this.isShowPlayBtn = this.hideType == 2?false:true
				this.deviceLogOut()
				this.videoContext.stop();
				if (this.isPush) {
					this.pushVideoContext.stop()
					this.isPush = false
					if(this.tempIsMute){
						this.tempIsMute = false
						this.isMute = true
						this.rightList.forEach((item)=>{
							if(item.id == 'sound'){
								item.icon = this.soundOffIcon
							}
						})
					}
					this.talkIcon = this.talkStausIcon.off[this.pageKey]
				}
				clearInterval(this.timer);
				this.timer = null
				clearInterval(getApp().globalData.keepTimer);
				getApp().globalData.keepTimer = null
				if(!this.isShowLightSleepModal){
					if(page[page.length - 1].$page.fullPath.includes('live-lexin') || page[page.length - 1].$page.fullPath.includes('live-familyCall')){
						this.LightSleepStatus = true
						this.isShowLightSleepModal = true;
						this.islivePlayLinkData = false
					}
				}
			},
			closeSleepStatusPopup(type){
				if(type == 'LightSleep'){
					this.LightSleepStatus = false
					this.isShowLightSleepModal = false
				}
				if(type == 'DeepSleep'){
					this.DeepSleepStatus = false
					this.isShowDeepSleepModal = false
					this.backAction()
				}
				if(type == 'noData'){
					this.noDataStatus = false
					this.continuePlay()
				}
				if(type == 'back'){
					this.backAction()
				}
				if(type == 'closeTalkStatus'){
					this.clickTalkStatus = false
				}
			},
			continuePlay(type){
				console.log('继续播放===',type,this.playType);
				if(this.playOrNot == 'suspend'){
				    this.isShowBg = false
			    }
				this.deviceStatus = 'WakeUp'
				if(this.playType == 1){
					this.disConnectCount = 0
					this.isFirstFrame = false
					this.livestream()
				}else{
					this.loginOrAuto();
					if(type == 'videoTalk'){
						this.getTwoWayVideoUrl()
					}else{
						if(this.isSupportSpeak){
							this.getTalkBackUrl()
						}
					}
				}
				this.isShowPlayBtn = false
				this.videoContext.play()
				this.$logs({info: '继续播放',playType:this.playType},'error')
			},
			//获取设备支持的属性列表
			getDeviceTypePropList(){
				let data = {
				    pid: this.device.pid,
				    page: 1,
				    limit: 999
				};
				getApp().globalData.api.getDeviceTypePropListByPageForApp(data, (result) => {
					let mainStream = false
					let extraStream = false
					let nonMic = false   //无麦克风
					let nonSpeaker = false //无扬声器
					result.data.forEach((item)=>{
						if(item.propCode == 'fullDuplex' || item.propCode == 'halfDuplex '){
							this.isSupportSpeak = true
						}
						if(item.propCode == 'mainStream'){
							mainStream = true
						}
						if(item.propCode == 'extraStream'){
							extraStream = true
						}
						if(item.propCode == 'supportVideoCall' || item.propCode == 'supportAudioCall'){
							this.isSupportVideoTalk = true
						}
						if(item.propCode == "powerSavingMode"){
							this.powerSavingMode = item
						}
						if(item.propCode == "nonSpeaker"){
							nonSpeaker = true
						}
					})
					let page = getCurrentPages()
					let flag = page[page.length - 1].$page.fullPath.includes('live-familyCall')
					if(!flag&&this.isSupportSpeak){
						this.getTalkBackUrl()
					}
					if(!mainStream || !extraStream){
						this.rightList.forEach((item,index)=>{
							if(item.id == 'HD'){
								this.rightList.splice(index,1)
								this.stream = '0'  
							}
						})
                    } else { // 支持主辅码流切换
                        this.streamSwitch = true
                    }					
					if(nonSpeaker){
						this.rightList.forEach((item,index)=>{
							if(item.id == 'sound'){
								this.rightList.splice(index,1)
							}
						})
					}
					this.loginOrAuto()
				});
			},
			// 获取wifi信号
			getDevicePropStatus(props){
				let data = {
					"sn": this.device.deviceNo,
					"props": [props]
				};
				getApp().globalData.api.getDevicePropStatus(data, (result) => {
					if(result.wifiSignal){
						this.wifiUrl = convertdBm2RSSI(result.wifiSignal,3)
					}
					if(result.batteryPower){
						this.bl = result.batteryPower>100?100:result.batteryPower
					}
					this.$logs({
						info: '获取WiFi信号和电量getDevicePropStatus',
						data:data,
						result: result,
					}, 'error')
				});
			},
			//关闭各种连接（跳转到消息页面,息屏、退到后台、杀死小程序等）
			closeAllLinks(hideType){
				uni.hideLoading()
				this.$logs({info:'退出预览页关闭各种连接',data:getApp().globalData.keepTimer,isLogin:this.isLogin,isLogout:this.isLogout,hideType:hideType})
				this.videoContext.stop();
				this.pushVideoContext.stop()
				this.isShowPlayer = false
				this.isShowPush = false
				if(this.isLoginSuccess){
					if(hideType!=3){
						this.closeLivestream();
					}
				}
				if(hideType == 1){
					if(this.isLogin){
						this.deviceLogOut()
					}
					clearInterval(this.timer);
					this.timer = null
					clearInterval(getApp().globalData.keepTimer);
					getApp().globalData.keepTimer = null
				}
				if (this.isPush) {
					this.pushVideoContext.stop()
					this.isPush = false
					if(this.tempIsMute){
						this.tempIsMute = false
						this.isMute = true
						this.rightList.forEach((item)=>{
							if(item.id == 'sound'){
								item.icon = this.soundOffIcon
							}
						})
					}
					this.talkIcon = this.talkStausIcon.off[this.pageKey]
				}
				clearInterval(this.pullTimer)
			},
			getBarHeight() {
				const res = uni.getSystemInfoSync()
				if (res.platform === 'ios') {
					return 44 + res.statusBarHeight
				} else if (res.platform === 'android') {
					return 48 + res.statusBarHeight
				} else {
					return 0;
				}
			},
			//获取可视区域高度
			getClineHeight() {
				uni.getSystemInfo({
					success: (res => {
						this.clientHeight = res.windowHeight - this.getBarHeight();
						this.captureBottom = res.safeAreaInsets.bottom
					})
				});
			},
			backAction() {
				if(this.pathType == 3){
					uni.switchTab({
						url: '/jvss/pages/device/home'
					})
				}else{
					uni.navigateBack({})
					this.getLivePlayerSnapShot(1,()=>{
					})
					clearInterval()
				}
			},
			//获取预览视频的观看人数
			getStreamConnectionsNum(){
				let token = this.device.token
				let str = this.url.split(':')[1]
				let data = {
					liveAddress: str.split('//')[1],
				};
				getApp().globalData.api.getStreamConnectionsNum(data,token,(result)=>{
					this.viewerNum = result.num
					console.log('观看人数：',result);
				})
			},
			// 获取电量协议接口
			getTailoredConfig() {
				let token = this.device.token
				let data = {
					"sn": this.device.deviceNo,
					"configs": []
				};
				getApp().globalData.api.getTailoredConfig(data, token, (result) => {
					this.TailoredInfo = result;
					let wifiNum = 1;
					if (result.bas != 3) {
						this.bal = result.bal;
					}
					if (result.bs != 3) {
						this.bl = result.bl;
					}
					if(result.wsl){
					    if (result.wsl <= 25) {
                            wifiNum = 1
                        }
                        if (result.wsl <= 50 && result.wsl > 25) {
                            wifiNum = 2
                        }
                        if (result.wsl <= 75 && result.wsl > 50) {
                           wifiNum = 3
                        }
					    if(result.wsl <= 100 && result.wsl > 75) {
					        wifiNum = 4
					    }
					    this.wifiUrl = 'https://statics.xmcsrv.net/weixin/wifi/' + 'wifiThree' + wifiNum + '.png'
					}
					this.douCamStat = result.DouCamStreamInfo&&result.DouCamStreamInfo.DouCamStat
					this.supportSwitchType = result.DouCamStreamInfo&&result.DouCamStreamInfo.SupportSwitchType || []
					this.isSupportVideoTalk = result.SystemFunction&&result.SystemFunction.OtherFunction.SupportVideoTalk || false
					if(!this.twoWayVideoUrl&&this.isSupportVideoTalk){
						// this.getTwoWayVideoUrl()
					}
					this.$forceUpdate()
					this.$logs({
						info: '获取WiFi信号和电量getTailoredConfig',
						data:data,
						result: result,
					}, 'error')
				});
			},
			colorbg(e) {
				if (e > 20) {
					return '#FF0025'
				} else {
					return '#FF5800'
				}
			},
			//设备退出
			deviceLogOut() {
				let token = this.device.token
				let data = {
					Name: 'Logout',
				};
				getApp().globalData.api.deviceLogOut(data, token, (result) => {
					console.log(result, '登出')
					this.$logs({info:'预览页退出登录',data:getApp().globalData.keepTimer,isLogin:this.isLogin,isLogout:this.isLogout,res:result})
				});
			},
			// 静音开关按钮
			onBindtapMuted() {
				this.isMute = !this.isMute
				if (this.isMute) {
					this.mutedIcon = 'https://statics.xmcsrv.net/weixin/soundoff2.png'
				} else {
					this.mutedIcon = 'https://statics.xmcsrv.net/weixin/soundon.png'
				}
			},
			// 处理对讲逻辑
			dealwithSpeak(){
				this.isPush = !this.isPush
				if (this.isPush) {
					if(this.isMute){
						this.tempIsMute = true
						this.isMute = false
						this.rightList.forEach((item)=>{
							if(item.id == 'sound'){
								item.icon = this.soundOnIcon
							}
						})
					}
					this.talkIcon = this.talkStausIcon.on[this.pageKey]
					this.pushVideoContext.start()
					uni.showToast({
						title: '开始对讲',
						icon: 'none'
					})
					//如果是来电进来
					if(this.playOrNot == 'suspend'){
				        this.continuePlay()//点击对讲播放视频
			        }
				} else {
					if(this.tempIsMute){
						this.tempIsMute = false
						this.isMute = true
						this.rightList.forEach((item)=>{
							if(item.id == 'sound'){
								item.icon = this.soundOffIcon
							}
						})
					}
					this.talkIcon = this.talkStausIcon.off[this.pageKey]
					this.pushVideoContext.stop()
					uni.showToast({
						title: '对讲结束',
						icon: 'none'
					})
				}
			},
			//开始推送
			startPush() {
				console.log('开始对讲');
				this.isPush = true
				this.talkIcon = this.talkStausIcon.on[this.pageKey]
				if(this.isMute){
					this.tempIsMute = true
					this.isMute = false
					this.rightList.forEach((item)=>{
						if(item.id == 'sound'){
							item.icon = this.soundOnIcon
						}
					})
				}
				if(this.talkUrl){
					this.pushVideoContext.start()
					uni.showToast({
						title: '开始对讲',
						icon: 'none'
					})
				}else{
					this.getTalkBackUrl((url)=>{
						if(url){
							this.pushVideoContext.start()
							uni.showToast({
								title: '开始对讲',
								icon: 'none'
							})
						}
					},1)
				}
				
			},
			//停止推送
			stopPush() {
				console.log('停止对讲');
				this.isPush = false
				this.talkIcon = this.talkStausIcon.off[this.pageKey]
				if(this.tempIsMute){
					this.tempIsMute = false
					this.isMute = true
					this.rightList.forEach((item)=>{
						if(item.id == 'sound'){
							item.icon = this.soundOffIcon
						}
					})
				}
				this.pushVideoContext.stop()
				uni.showToast({
					title: '对讲结束',
					icon: 'none'
				})
			},
			// 网络状态变化
			netstatusChange(e){
				console.log('网络状态==',e.detail.info);
				let info = e.detail.info
				if(info.videoBitrate == 0 && info.audioBitrate == 0 && this.islivePlayLinkData){
					this.$postPointData({code:'402006', eventName:'play_media_net_no_nomal_data'})
				}
				if(info.videoBitrate == 0 && info.audioBitrate > 0 && this.islivePlayLinkData){
					this.$postPointData({code:'402005', eventName:'play_media_net_no_nomal_data'})
				}
				this.netstatus = e.detail.info
				this.netSpeed = info.netSpeed != 0 ?(Number(info.netSpeed)/8).toFixed(2) + ' KB/S':this.netSpeed
				if(this.isStartPlay){
					if(info.netSpeed == 0){
						this.disConnectCount ++
						if(this.disConnectCount == 15){
							this.videoContext.stop();
							this.isShowPlayBtn = true
							this.playType = 1
							uni.showToast({
								title:'网络已断开，请重试',
								icon:'none'
							})
						}
						this.$logs({info:'网络状态变化-网络已断开',disConnectCount:this.disConnectCount})
					}else{
						this.playType = 0
						this.disConnectCount = 0
					}
				}
				this.videoFPS = info.videoFPS
				this.netJitter = info.netJitter
				this.netQualityLevel = info.netQualityLevel
				this.vSumCacheSize = info.vSumCacheSize
				this.videoCache = info.videoCache
				this.audioCache = info.audioCache
				this.avPlayInterval = info.avPlayInterval
				this.avRecvInterval = info.avRecvInterval
			},
			bindaudiovolumenotify(e){
				// console.log('播放声音状态===', e.detail);
			},
			// 播放状态变化事件
			statechange(e) {
				console.log('拉流状态===', e.detail,this.getCurrentTime());
				let code = e.detail.code;
				let message = e.detail.message
				this.livePlayCode = e.detail;
				const codesToTrack = [3001, 3002, 3003, 3005, -2301, -2302];
				if (codesToTrack.includes(code)) {
				  this.$postPointData({ code: '402004', eventName: 'play_media_net_no_any_data' });
				}
				if (code == 2105) {
				}
				if(code == 2002){
					this.$logs({info: '已经连接RTMP服务器,开始拉流',code:code})
				}
				if(code == 2003){
					this.islivePlayLinkData = true
					this.$logs({info: '拉流状态2003网络接收到首个视频数据包',code:code})
				}
				if (code == 2004) {
					this.isLoading = false;
					uni.hideLoading()
					this.isStartPlay = true
					this.isFirstFrame = true
					if(this.playOrNot != 'suspend'){
				        this.isShowBg = false
			        }
					clearInterval(this.pullTimer)
					// let page = getCurrentPages()
					// let flag = page[page.length - 1].$page.fullPath.includes('live-familyCall')
					// if(flag){
					// 	this.switchCamera()
					// }
					this.$logs({info: '拉流状态2004开始播放',code:code})
					if(message == 'Begin play'){
						this.$postPointData({code:'602003', eventName:'play_start_by_rps'})
					}
				}
				if(code == 2032){
					this.$logs({info: '视频渲染首帧事件',code:code})
				}
				if(code == 2101){
					this.$logs({info: '当前视频帧解码失败',code:code})
					this.$postPointData({code:'402003', eventName:'play_start_error'})
				}
				if(code == 3002){
					this.$logs({info: 'RTMP服务器连接失败',code:code})
					this.$postPointData({code:'402003', eventName:'play_start_error'})
					this.$postPointData({code:'600820', eventName:'page_monitor_error_info'})
				}
				if(code == 3003){
					this.$postPointData({code:'402003', eventName:'play_start_error'})
					this.$logs({info: 'RTMP服务器握手失败',code:code})
				}
				if(code == 2033){
					// this.$postPointData({code:'402003', eventName:'play_start_error'})
					uni.hideLoading()
				}
				if (code == 2103) {
					// this.livestream();
					console.log(this.count,'定时')
					// if (this.count == 0) {
					// 	this.liveTimer = setInterval(() => {
					// 		this.count++;
					// 		if (this.count == 10) {
					// 			clearInterval(this.liveTimer);
					// 		}
					// 	}, 1000)
					// }
				}
				if ( code == -2301) {
					this.isLoading = true
					this.loadingText = '缓冲中...'
					console.log('重新推流',this.videoContext);
					this.livestream()
					this.videoContext.play()
					this.$logs({apiUrl: '拉流状态变化-2301',code:code,deviceStatus:this.deviceStatus},'error')
				}
				if(this.deviceStatus == 'DeepSleep' || this.deviceStatus == 'LightSleep'){
					this.videoContext.stop()
				}
			},
			error(e) {
				console.error('live-player error:', e.detail.errMsg)
				this.isShowPlayer = false
				setTimeout(() => {
					this.isShowPlayer = true
					this.$logs({info: '重新挂载live-player组件',error:e},'error')
				}, 2000)
				if(e.detail.errMsg == 'insertLivePlayer:fail phone is calling'){
					this.$logs({info:'live-player组件播放报错1',error:e},'error')
					setTimeout(()=>{
						this.livestream()
					},5000)
				} else {
					this.$logs({info:'live-player组件播放报错2',error:e},'error')
					setTimeout(() => {
						this.livestream()
					}, 5000)
				}
				// this.$logs({info:'live-player组件播放报错',error:e},'error')
			},
			statechange2(e) {
				console.log('推流live-pusher code:', e.detail,this.getCurrentTime())
				let code = e.detail.code
				if(code == 1002){
					//开始推流
					if(this.isOpenVideoTalk){
						this.talkTime = 180
					}
				}
				if(code == 3002 || code == -1307){
					if(this.isSupportVideoTalk&&this.isOpenVideoTalk){
						this.getTwoWayVideoUrl()
					}else{
						this.getTalkBackUrl((res)=>{
							this.talkUrl = res
							if(this.isPush){
								this.pushVideoContext.start()
							}
							this.$logs({apiUrl:'推流状态变化3002或-1307',code: e.detail,isPush:this.isPush,talkUrl:this.talkUrl},'error')
						})
					}
				}
				if(code == 1002){   //已经与服务器握手完毕，开始推流
					this.$logs({apiUrl:'推流状态变化1002开始推流'},'error')
				}
				this.$logs({apiUrl: '推流状态变化live-pusher code',code: e.detail},'error',false)
			},
			error2(e) {
				console.error('推流live-pusher error:', e.detail.errMsg)
				this.$logs({apiUrl: '推流错误事件error',error: e.detail},'error')
			},
			// live-pusher网络状态通知事件
			netstatusChangePusher(e){
				console.log('对讲网络状态变化',e);
			},
			//确认开锁  type为2时 是新预览页立即开锁的类型 ,deviceType为‘lexin‘时 不提示开锁成功
			confimeUnlock(type,deviceType,msgTime) {
				uni.showLoading({
					title: '正在开锁'
				})
				uni.setStorageSync('isCurrentUserUnlock',true)
				let token = this.device.token;
				let data = {
					sn: this.device.deviceNo,
					props: {
						"doorLock": {
							"remoteOneKeyUnlock": 1
						}
					}
				};
				getApp().globalData.api.remoteUnlock(data, token, (result) => {
					uni.hideLoading();
					this.cancel()
					if (result.Ret === 100) {
						if(deviceType == 'lexin'){
							let cacheData = uni.getStorageSync(this.device.deviceNo) || {}
							cacheData.lockTime = new Date().getTime()
							cacheData.msgTime = msgTime
							uni.setStorageSync(this.device.deviceNo,cacheData)
						}else{
							uni.showToast({
								title: '开锁成功',
							})
						}
					} else {
						uni.showToast({
							title: '开锁失败',
							icon: 'error'
						});
					}
					if(type == 2){
						this.$refs.bottomPopup.close()
					}
				});
			},
			// 取消开锁
			cancel() {
				this.$refs.inputDialog.close()
			},
			//展示画质弹框
			changeQuality() {
				this.isShowHD = !this.isShowHD
			},
			//切换高清或标清
			selectHd(item) {
				this.$postPointData({code:'600806', eventName:'click_monitor_video_type', screen_orientation:false})
				this.hdText = item.label
				// this.stream = item.id
				this.isShowHD = false
				this.onBindtapSDFHD()

			},
			// 开锁
			unlockClick() {
				if (!this.isLogin) {
					this.$refs.deviceLogin.submit(this.device.devUserName, this.device.devPassWord,this.device.adminToken,'twice')
					uni.$on('twiceSubmitSuccess',(res)=>{
						this.loginSuccessConfimrUnlock()
					})
					// uni.showToast({
					// 	title: '设备没有登录成功，暂不能开锁',
					// 	icon: 'none'
					// })
					// return
				}else{
					this.loginSuccessConfimrUnlock()
				}
			},
			loginSuccessConfimrUnlock(){
				let constant = getApp().globalData.constant;
				let LOCK3 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK3; //博克 AHD
				let LOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4; // 博克乐鑫XM650主PID
				let LOCK7 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7; // 博克乐鑫主pid
				let LOCK11 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK11; // 博克乐鑫新UI主pid
				// let LOCK15 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK15;// 博克乐鑫
				// let LOCK16 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK16; // 博克乐鑫
				if((this.device.parentPid == LOCK7 || this.device.parentPid == LOCK3 || this.device.parentPid == LOCK4 || this.device.parentPid == LOCK11)&&this.appletIdentify!=this.generalIdentify){
					this.getMsgList()
					this.$logs({info:'开锁需要判断60s内是否有门铃来电消息',device:this.device})
				}else{
					this.$refs.inputDialog.open()
					this.$logs({info:'开锁不需要判断60s内有门铃来电消息',device:this.device})
				}
			},
			getMsgList() {
				let currentDate = new Date().toJSON().split('T')[0]
				let startTime = getBeforeDay(0) + ' ' +'00:00:00'
				let endTime = getBeforeDay(0) + ' ' + '23:59:59'
				let token = this.device.token
				let data = {
					sn: this.device.deviceNo,
					startTime: startTime,
					endTime: endTime,
					AlarmEvent:'',
					pageSize:10,
					pageNum:1
				}
				getApp().globalData.api.getLockAlarmMSgList(data, token, (result) => {
					let list = result.AlarmArray ||  []
					let callList = []
					let remoteLockArr = []
					list.forEach((item)=>{
						if(item.AlarmEvent.includes('DoorLockCall')){
							callList.push(item)
						}
						if (this.isJSON(item.AlarmMsg)) {
						    let AlarmMsg = JSON.parse(item.AlarmMsg)
						    if(AlarmMsg.MsgType == 'Remote'){
							    remoteLockArr.push(item)
						    }
						}
					})
					if(callList.length>0){
						let currentTime = new Date().getTime()
						let msgTime = new Date(callList[0].AlarmTime.replaceAll('-', '/')).getTime()
						let lastUnlockTime = 0
						if(remoteLockArr.length>0){
							lastUnlockTime = new Date(remoteLockArr[0].AlarmTime.replaceAll('-', '/')).getTime()
						}
						if(Number(msgTime)+(60*1000)>currentTime){
							if(Number(msgTime)<Number(lastUnlockTime)){
								uni.showToast({
									title:'请按锁端门铃按键发起远程开锁请求',
									icon:'none'
								})
							}else{
								this.$refs.inputDialog.open()
								this.$logs({info:'可以开锁',msgTime:msgTime,currentTime:currentTime,lastUnlockTime:lastUnlockTime})
							}
						}else{
							uni.showToast({
								title:'请按锁端门铃按键发起远程开锁请求',
								icon:'none'
							})
							this.$logs({info:'开锁1',msgTime:msgTime,currentTime:currentTime,lastUnlockTime:lastUnlockTime},'error')
						}
					}else{
						uni.showToast({
							title:'请按锁端门铃按键发起远程开锁请求',
							icon:'none'
						})
						this.$logs({info:'开锁2',callList:callList,res:result},'error')
					}
				})
			},
			isJSON(str) {
				if (typeof str == 'string') {
					try {
						var obj = JSON.parse(str);
						if (typeof obj == 'object' && obj) {
							return true;
						} else {
							return false;
						}
					} catch (e) {
						return false;
					}
				}
			},
			//截图
			getCaptureImg(){
				let token = this.device.token
				let data = {
					Name: "OPSNAP",
					OPSNAP: {
						Channel: 0,
						PicType: 0
					}
				}
				getApp().globalData.api.capture(data,token,(result) => {
					console.log('截图=====',result);
					this.captureUrl = result.image
				})
			},
			//检查相册权限
			checkPhotoAuth() {
				wx.getSetting({
					success: (res) => {
						let authSetting = res.authSetting
						if (authSetting['scope.writePhotosAlbum'] === false) {
							wx.showModal({
								title: '您未开启相册授权',
								content: '请在小程序系统设置中打开相册授权，以便我们为您提供更好的服务',
								success: (res) => {
									if (res.confirm) {
										wx.openSetting()
									}
								}
							})
						}else{
							this.getLivePlayerSnapShot()
						} 
				    }
				})
			},
			//截图
			getLivePlayerSnapShot(type,callback){
				this.$postPointData({code:'600804', eventName:'click_monitor_capture',screen_orientation:false,checkState:null})
				this.tryCaptureNum = 0
				this.videoContext.snapshot({
					quality:'raw',
					sourceType:'stream',
					success:(res)=>{
						console.log('截图成功',res);
						if(type == 1){
							let cacheData = uni.getStorageSync(this.device.deviceNo)
							let capture = {
								url:res.tempImagePath,
								time:new Date().getTime()
							}
							if(!cacheData){
								uni.setStorageSync(this.device.deviceNo,{previewCapture:capture})
							}else{
								cacheData['previewCapture'] = capture
								uni.setStorageSync(this.device.deviceNo,cacheData)
							}
							if (typeof callback === 'function') {
								callback()
							}
							return
						}
						this.tryCaptureNum = 0
						this.isCapture = true
						setTimeout(()=>{
							this.isCapture = false
						},5000)
						this.captureUrl = res.tempImagePath
                        if(this.streamSwitch){
							uni.saveImageToPhotosAlbum({
								filePath:res.tempImagePath,
								success: (result) => {
									uni.showToast({
										title:'保存相册成功',
										icon:'none'
									})
								},
								fail: (error) => {
									uni.showToast({
										title:'保存相册失败',
										icon:'none'
									})
									console.log('保存相册失败',error);
								}
							})
						}else{
							this.canvasDrawImage(res.tempImagePath)
						}
					},
					fail:(err)=>{
						console.log('截图失败',err);
						if(type == 1){
							callback()
							return
						}
						this.tryCaptureNum ++
						if(this.tryCaptureNum<8){
							this.getLivePlayerSnapShot()
						}else{
							uni.showToast({
								title:'截图过于频繁，请稍候再试',
								icon:'none'
							})
						}
						this.$logs({apiUrl:'截图失败',num:this.tryCaptureNum,err:err},'error')
					}
				})
			},
			//分享截图
			shareCapture(){
				if(this.phoneType == 'iPad') {
					this.$refs.share.open()
					return
				}
				let img = this.canvasImgPath || this.captureUrl
				wx.showShareImageMenu({
					path:img,
					success: (res) => {
						uni.showToast({
							title:'操作成功',
							icon:'none'
						})
					},
					fail: (err) => {
						// uni.showToast({
						// 	title:'分享失败',
						// 	icon:'none'
						// })
					}
				})
			},
			//云回放 云事件 设置
			clickFunc(item) {
				switch (item.id){
					case 'HD':
						this.changeStream(item)
						break;
					case 'capture':
						if(this.deviceStatus == 'LightSleep'){
							uni.showToast({
								title:'需要在视频播放状态下才能操作',
								icon:'none'
							})
							return
						}
						// this.getLivePlayerSnapShot()
						this.checkPhotoAuth()
						break;
					case 'msg':
						// this.dealWithTap()
						uni.navigateTo({
							url: `${item.url}?device=${encodeURIComponent(JSON.stringify(this.device))}`
						})
						break;
					case 'sound':
						this.changeSound(item)
						break;
					case 'setting':
						// this.dealWithTap()
						this.hideType = 2
						this.$postPointData({code:'600807', eventName:'click_monitor_setting'})
						uni.navigateTo({
							url: `${item.url}?device=${encodeURIComponent(JSON.stringify(this.device))}&powerSavingMode=${encodeURIComponent(JSON.stringify(this.powerSavingMode))}`
						})
						break;
					case 'cloud':
						if(this.device.xmcCssVid.support){
							let buyUrl = '/jvss/pageCloud/buy/default?classifyId=xmc.css'+'&sn=' + this.device.deviceNo
							this.rightList.forEach((item,index)=>{
								if(item.id == 'cloud'){
									item.url = !this.device.xmcCssVid.enable?buyUrl:this.device.xmcCssVid.isExpire?'/jvss/pagesDevice/device/device-live/door-lock/msgDetail':buyUrl
								}
							})
						}
						uni.navigateTo({
							url: `${item.url}?device=${encodeURIComponent(JSON.stringify(this.device))}`
						})
						break;
					case 'switch':
						this.switchCamera()
					default:
						break;
				}
			},
			//切换多目摄像头
			switchCamera(type){
				let switchTypeIndex = 0
				let currentIndex = this.supportSwitchType.findIndex(item=>item == this.switchType)
				if(currentIndex == this.supportSwitchType.length -1){
					currentIndex = 0
				}else{
					currentIndex ++
				}
				// 0x00000001代表摄像头1 0x00000002代表摄像头2  0x00000004代表摄像头3  0x00000003代表摄像头1+摄像头2拼接
				// 0x00000010摄像头内中  0x00000001 摄像头外中
				let switchType = this.supportSwitchType[currentIndex]
				if(type !=1){
					uni.showLoading({
						title:'切换中'
					})
				}else{
					let index = this.supportSwitchType.findIndex(item=>item == '0x00000010')
					switchType = index!=-1?'0x00000010':this.supportSwitchType[currentIndex]
				}
				let data = {
					Name:'OPMultiCameraSwitch',
					OPMultiCameraSwitch:{
						SwitchType:switchType//this.supportSwitchType[currentIndex]
					},
				}
				this.getMulitiCameraLive(data,switchType)
			},
			// 多目门锁视频编码画面切换能力
			getdoorLocktability(Name) {
				let data = {
					Name: Name
				};
				let token = this.device.token;
				getApp().globalData.api.getability(data, token, (result) => {
					console.log('获取门锁能力集',result);
					if(result.data.code == 2000){
						let res = result.data.data
						if(res.Ret == 100){
							if(Name == 'MultiCamera'){
								this.supportSwitchType = res.MultiCamera&&res.MultiCamera.SupportSwitchType || []
								this.maxCameraNum = res.MultiCamera&&res.MultiCamera.MaxCameraNum
								this.currentCameraNum = res.MultiCamera&&res.MultiCamera.CurentCameraNum
								if(this.supportSwitchType.length>1){
									let index = this.rightList.findIndex(item=>item.id == 'switch')
									if(index ==-1){
										this.rightList.push({icon:'https://statics.xmcsrv.net/weixin/live/switchCamera2.png',id:'switch'},)
									}
								}
								if(this.supportSwitchType.length > 0){
									let data = {
										Name:'OPMultiCameraGet',
									}
									this.getMulitiCameraLive(data)
								}
							}
							if(Name == 'DecoderPram'){
								let decoderPram = res.DecoderPram
								this.videoWidth = decoderPram.Video[0].Res[0].W
								this.videoHeight = decoderPram.Video[0].Res[0].H
								this.fps = decoderPram.Video[0].Res[0].FPS  || '12'
								this.videoPlayer = decoderPram.Video[0].Enc || 'h264'
								this.audioCodePlayer = decoderPram.Audio[0].Enc || 'g711a'
								this.audioKHZPlayer = decoderPram.Audio[0].SR[0] || '8000'
								this.audioAccuracyPlayer = (decoderPram.Audio[0].SB&&decoderPram.Audio[0].SB[0]) || '16'
								// this.videoWidth = 320//532
								// this.videoHeight = 576//320
								// this.fps = 12
								console.log('宽高帧率',this.videoWidth,this.videoHeight,this.fps);
								this.isSupportVideoTalk = true
								// if(this.isSupportVideoTalk){
								// 	this.getTwoWayVideoUrl()
								// }
								let page = getCurrentPages()
								let flag = page[page.length - 1].$page.fullPath.includes('live-familyCall')
								if(flag){
									this.getTwoWayVideoUrl()
									this.isOpenVideoTalk = true
								}
							}
							
						}else if(res.Ret == 527){
							//消息发给主控失败了，需要重新唤醒主控（650+3861L门锁用）
							this.wakeup(()=>{
								this.getdoorLocktability(Name)
							})
						}else if(res.Ret !=103 && res.Ret !=102){
							uni.showToast({
								title:getApp().globalData.errCodeMsg.RetCodeMsg[res.Ret] || res.RetMsg,
								icon:'none'
							})
						}
					}else{
						uni.showToast({
							title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
							icon:'none'
						})
					}
				},false,false);
			},
			// 多目门锁视频编码画面获取
			getMulitiCameraLive(data,type) {
				let token = this.device.token
				getApp().globalData.api.opdev(data, token, (result) => {
					uni.hideLoading()
					if(result.data.code == 2000){
						let res = result.data.data
						if(res.Ret == 100){
							if(data.Name == 'OPMultiCameraGet'){
								this.switchType = res.OPMultiCameraGet.SwitchType
								let page = getCurrentPages()
								let flag = page[page.length - 1].$page.fullPath.includes('live-familyCall')
								if(flag){
									this.switchCamera(1)
								}
							}
							if(data.Name == 'OPMultiCameraSwitch'){
								// uni.showToast({
								// 	title:'切换成功',
								// 	icon:'none'
								// })
								this.switchType = type
							}
						}else if(res.Ret == 170){
							uni.showModal({
								title:'提示',
								showCancel:false,
								content:'检测到即将切换的镜头已关闭,暂不可切换',
								success(res){
									
								}
							})
						}else if(res.Ret == 527){
							this.wakeup(()=>{
								this.getMulitiCameraLive(data,type)
							})
						}
					}else{
						uni.showToast({
							title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
							icon:'none'
						})
					}
					
				},false,false)
			},
			//切换主辅码流
			changeStream(item){
				this.isHd = !this.isHd
				console.log(this.isHd, '切换是不是高清',item,this.rightList)
				let data = {
					deviceNo:this.device.deviceNo,
					stream:null
				}
				this.rightList.forEach((z)=>{
					if(z.id == item.id){
						if(this.isHd){
							z.icon = 'https://statics.xmcsrv.net/weixin/live/HD.png'
							this.stream = '0'
							data.stream = '0'
							uni.setStorageSync('definition',data)
						}else{
							z.icon = 'https://statics.xmcsrv.net/weixin/live/SD.png'
							this.stream = '1'
							data.stream = '1'
							uni.setStorageSync('definition',data)
						}
					}
				})
				this.onBindtapSDFHD()
				uni.showLoading({
					mask:true,
					title:'切换中...'
				});
			},
			//开关静音
			changeSound(item){
				this.isMute = !this.isMute
				this.isClose = !this.isClose
				if (this.isMute) {
					item.icon = this.soundOffIcon
				} else {
					item.icon = this.soundOnIcon
				}
			},
			dealWithTap(){
				this.deviceLogOut()
				this.autoPause = true
				if(!this.isMute){
					this.isClose = true
					this.isMute = !this.isMute
				}
			},
			// 跳转到临时密码
			toTemporary() {
				this.hideType = 3
				if(!this.isLogin){
					this.$refs.deviceLogin.submit(this.device.devUserName, this.device.devPassWord,this.device.adminToken,'twice')
					uni.$on('twiceSubmitSuccess',(res)=>{
						uni.navigateTo({
							url: `./temporaryBk?device=${encodeURIComponent(JSON.stringify(this.device))}`
						})
					})
				}else{
					uni.navigateTo({
						url: `./temporaryBk?device=${encodeURIComponent(JSON.stringify(this.device))}`
					})
				}
			},
			//卡存录像  云存录像  卡存相册
			toDetail(item) {
				uni.navigateTo({
					url: `${item.url}?device=${JSON.stringify(this.device)}`
				})
			},
			// 关闭弹框
			closePopup() {
				this.$refs.popup.close()
			},
			// 循环对比获取当前设备，否则使用传参设备
			getCurrentDevice(options) {
				let device = options //JSON.parse(options.device);
				console.log('传值数据', device);
				// let deviceList = uni.getStorageSync('deviceList') || [];
				// this.deviceList = deviceList;
				// console.log('缓存数据', deviceList);
				// let bool = false;

				// for (let i = 0; i < deviceList.length; i++) {
				// 	const item = deviceList[i];
				// 	if (item.deviceNo === device.deviceNo) {
				// 		bool = true;
				// 		this.device = item
				// 		this.deviceList = deviceList
				// 		this.isCache = true
				// 		break;
				// 	}
				// }
				// console.log(bool, 'bool')
				// if (!bool) {
				// 	this.device = device
				// 	this.deviceList.push(device);
				if (device.devPassWord) {
					this.isCache = true
				} else {
					this.isCache = false
				}
				// }
				console.log(this.isCache, 'this.isCache')
			},

			/** ======================================================== 设备播放 流程 ================================================================ */
			getInit() {
				let sns = []
				sns.push(this.device.deviceNo)
				this.getDeviceStatus([this.device.token], this.deviceList);
				// this.getDeviceToken(sns)
			},

			// 获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				console.log('app:', getApp());
				getApp().globalData.api.getDeviceToken(data, (result) => {
					console.log('获取设备token:', result);
					// 遍历缓存更新当前设备的token
					this.device.token = result[0].token
					uni.setStorageSync('deviceToken',this.device.token)
					getApp().globalData.deviceToken = this.device.token
					this.deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.sn) {
								item.token = pro.token;
								this.device = item
							}
						});
					});
					// 根据token查询当前设置状态
					let tokenList = [];
					result.forEach((item) => {
						tokenList.push(item.token);
					});
					this.getDeviceStatus(tokenList, this.deviceList);
				});
			},
			// 获取设备状态
			getDeviceStatus(tokenList, deviceList) {
				const data = {
					token: tokenList
				};
				getApp().globalData.api.getNewDeviceStatus(data, (result) => {
					// 遍历缓存增加或更新当前设备的status
					deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.uuid) {
								this.$set(item, 'status', pro)
								this.device = item
							}
						});
					});
					// 遍历缓存更新BOSS中当前设备的token和status
					let bossDeviceList = uni.getStorageSync('bossDeviceList')
					bossDeviceList.forEach(item => {
						deviceList.forEach(pro => {
							if (item.deviceNo === pro.deviceNo) {
								item.token = pro.token
								item.status = pro.status
							}
						})
					})
					// 存储缓存
					uni.setStorageSync('deviceList', deviceList)
					uni.setStorageSync('bossDeviceList', bossDeviceList)
					this.getMore()
				});
			},
			// 第1步 根据传参过来的设备对象以及对象状态，做一系列的判断和准备操作
			getMore() {
				console.log('唤醒设备===================', this.device.status);
				let status = this.device.status; // 在线
				if (status.status === 'online') {
					// 低功耗设备-已休眠
					if (status.wakeUpStatus === 0) {
						// 支持远程唤醒
						if (status.wakeUpEnable === '1') {
							// this.loginOrAuto();
							// uni.showLoading({
							// 	title: '唤醒设备中...'
							// }); //唤醒设备
							// this.wakeup(() => {
							// 	uni.hideLoading({
							// 		success: (res) => {
							// 			this.loginOrAuto();
							// 		}
							// 	});
							// });
						}
						// 不支持远程唤醒（手动唤醒）
						else {
							uni.showModal({
								title: '提示',
								content: '该设备深度休眠中，需要手动唤醒！',
								showCancel: false,
								success: (res) => {
									uni.navigateBack({
										delta: 1
									});
								}
							});
						}
					} // 低功耗设备-已唤醒
					else if (status.wakeUpStatus === 1) {
						// this.loginOrAuto();
					} // 普通设备
					else {
						// this.loginOrAuto();
					}
				}
			},

			// 低功耗设备唤醒 唤醒主控 收到唤醒成功推送才能获取能力集以及切换多目摄像头
			wakeup(callback) {
				let data={
					sn:this.device.deviceNo,
					hostedControl:"1",//是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
				}
				getApp().globalData.api.wakeup(data,this.device.token, (result) => {
					this.$logs({apiUrl: '低功耗唤醒设备接口',data:result})
					callback();
				});
			},

			// 第2步 手动登录或自动登录
			loginOrAuto() {
				let time1 = this.getCurrentTime()
				this.$logs({info: '开始请求对讲和直播流地址',time:time1})
				uni.showLoading({
					title: '正在加载...',
					mask: true
				});
				// if(this.device.deviceNo!='406d741ad2e7f957'){
					this.livestream();
				// }
				// this.getTalkBackUrl()
				if (!this.isCache && !this.device.adminToken) {
					this.$refs.deviceLogin.open()
				} else {
					this.$refs.deviceLogin.submit(this.device.devUserName, this.device.devPassWord,this.device.adminToken)
				}
			},

			// 第3步 登录
			submit(options) {
				console.log(options, '登录按钮');
				// 缓存登录信息
				// if (!this.isCache) {
				// 	this.saveLoginInfo(options);
				// }
				if(this.isLogout){
					uni.$emit('getLoginSuccess', {
						deviceNo: this.device.deviceNo,
						token:this.device.token,
						isLogout:this.isLogout
					})
				}
				this.isLogin = true
				this.saveLoginInfo(options);
				// 云服务
				this.reqCaps();
				// 保活
				this.initKeepAlive();
				//双摄的获取能力集
				if(this.device.parentPid == LOCK9 || this.device.parentPid == LOCK22){
					let flag = Object.keys(this.device.status).includes('DevHostStatus') //主控状态：0 休眠， 1 唤醒  正式环境还没上
					// if(flag){
					// 	//支持主控唤醒
					// 	let devHostStatus = this.device.status.DevHostStatus
					// 	if(!devHostStatus){
					// 		this.wakeup(() => {
					// 			this.getdoorLocktability()
					// 		})
					// 	}
					// }
					this.wakeup(() => {
						this.getdoorLocktability('MultiCamera')
						this.getdoorLocktability('DecoderPram')
					})
				}
			},
			// 缓存登录信息
			saveLoginInfo(options) {
				let deviceList = uni.getStorageSync('deviceList') || [];
				this.device.devUserName = options.username;
				this.device.devPassWord = options.password;
				let isCache = false
				deviceList.forEach((item) => {
					if (this.device.deviceNo == item.deviceNo) {
						item.devUserName = options.username
						item.devPassWord = options.password
						isCache = true
					}
				})
				if (!isCache) {
					deviceList.push(this.device);
				}
				uni.setStorageSync('deviceList', deviceList);
			},
			// 第4步-1 保活
			// 20秒执行一次，当连续请求两次保活失败时，则不再保活
			initKeepAlive() {
				console.log('定时器：', this.timer);
				if (this.timer !== null) {
					clearInterval(this.timer);
					this.timer = null
				}
				getApp().globalData.keepTimer = setInterval(() => {
					this.keepAlive();
					// this.getTailoredConfig()
				}, 15000)
				this.timer = getApp().globalData.keepTimer
			},
			// 保活
			keepAlive() {
				let token = this.device.token;
				getApp().globalData.api.keepAlive(token, (result) => {
					// console.log('保活：', result);
					this.$logs({apiUrl:'保活接口',sn:this.device.deviceNo,token:token,result:result.data})
					if (result.data.code === 2000) {
						if (result.data.data.Ret === 100) {
							// 不需要操作
						} else {
							if (this.keepAliveCount === 0) {
								this.keepAliveCount = this.keepAliveCount + 1
								this.initKeepAlive();
							} else {
								clearInterval(this.timer);
							}
						}
					} else {
						if (this.keepAliveCount === 0) {
							this.keepAliveCount = this.keepAliveCount + 1
							this.initKeepAlive();
						} else {
							clearInterval(this.timer);
						}
					}
					if(this.isLogout){
						uni.$emit('getKeepAlive', {
							deviceNo: this.device.deviceNo,
							token:this.device.token,
							isLogout:this.isLogout
						})
					}
				});
			},

			// 第4步-2 获取设备直播地址
			livestream() {
				console.log('获取直播地址')
				this.$postPointData({code:'600818', eventName:'into_page_monitor'})
				let token = this.device.token;
				let data = {
					mediaType: 'hls',//hls
					channel: '0',
					stream: this.stream,
					protocol: 'ts',
					username: this.device.devUserName,
					devPwd: this.device.devPassWord,
					userToken: uni.getStorageSync('accessToken'),
					appKey: getApp().globalData.api.appKey,
					encryptType: 'DISABLE',
					// videoCode:'h264'
				};
				let constant = getApp().globalData.constant;
				if (this.device.parentPid === constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK5 || this.device.parentPid === constant
					.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK6 || this.device.parentPid === constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7) {
					data.videoCode = 'h264'
				}
				if (this.device.adminToken) {
					data.authentication = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				let reqTime = this.getCurrentTime()
				getApp().globalData.api.livestream(data, token, (result) => {
					// console.log('获取设备直播地址:', result.data); // 渲染层网络层错误
					uni.hideLoading()
					let time1 = this.getCurrentTime()
					// this.$logs({reqTime:reqTime,resTime:time1,apiUrl: '获取预览地址',sn:this.device.deviceNo,data:data,result:result.data,envVersion:__wxConfig.envVersion})
					
					let page = getCurrentPages()
					if(result.data.code == 2000){
						let Ret = result.data.data.Ret
						console.log('页面实例====live',page);
						if (result && (Ret === 100 || Ret === 104)) {
							console.log(result.data,'result.data')
							this.url = result.data.data.url
							this.autoplay = true
							// this.isPlay = true
							// this.videoContext.play()
							// #ifdef MP-WEIXIN
							console.log('走进来了？？？？？？？')
							this.isLoginSuccess = true;
							this.isLoading = false
							this.autoPause = true
							let second = 0
							if(page[page.length - 1].$page.fullPath.includes('live-lexin') || page[page.length - 1].$page.fullPath.includes('live1')){
								if(this.playOrNot != 'suspend'){
									uni.showLoading({
										title:'正在缓冲'
									})
								}
							}
							setTimeout(()=>{
								uni.hideLoading();
							},20000)
							this.pullTimer = setInterval(()=>{
								second ++
								if(second == 20){
									clearInterval(this.pullTimer)
									if(!this.isFirstFrame){
										if(page[page.length - 1].$page.fullPath.includes('live-lexin') || page[page.length - 1].$page.fullPath.includes('live1')){
											console.log('无视频数据===',page[page.length - 1].$page.fullPath.includes('live-lexin') || page[page.length - 1].$page.fullPath.includes('live1'));
											// uni.showToast({
											// 	title:'无视频数据，请重试',
											// 	icon:'none'
											// })
											this.noDataStatus = true
											this.isShowPlayBtn = true
											this.playType = 1
											// this.videoContext.stop();
										}
									}
								}
								// console.log('缓存时间',second);
							},1000)
							
							this.tryCount = 0
							this.tryTokenCount = 0
							if(this.isLogout){
								uni.$emit('getLiveStream', {
									deviceNo: this.device.deviceNo,
									token:this.device.token,
									stream: this.stream,
									PassWord: this.device.devPassWord,
									UserName: this.device.devUserName,
									encryptType: 'DISABLE',
									authentication: this.device.adminToken,
									isLogout:this.isLogout
								})
							}
							this.$forceUpdate()
							// uni.hideLoading()
							this.liveState = true;
							clearInterval(this.liveTimer);
							this.count == 0;
							this.getStreamConnectionsNum()
							this.$logs({apiUrl: '获取预览地址成功',sn:this.device.deviceNo,data:data,result:result.data},'error')
							// #endif
						}
						//用户名密码错误
						else if (Ret == 106) {
							this.isLoginSuccess = false
							this.$refs.deviceLogin.open()
							this.$logs({apiUrl: '获取预览地址',sn:this.device.deviceNo,data:data,result:result.data},'error')
						}else if(Ret == 137){
							this.tryTokenCount ++
							if(this.tryTokenCount == 1){
								this.getAdminToken()
							}else if(this.tryTokenCount == 2){
								setTimeout(()=>{
									this.getAdminToken()
								},5000)
							}else if(this.tryTokenCount == 3){
								setTimeout(()=>{
									this.getAdminToken()
								},15000)
							}else{
								if(page.length ==2){
									uni.showToast({
										title:getApp().globalData.errCodeMsg.RetCodeMsg[Ret] || result.data.data.retMsg,
										icon:"none"
									})
								}
							}
							this.$logs({apiUrl: '获取预览地址137',sn:this.device.deviceNo,data:data,result:result.data},'error')
						}
						// 其他错误情况
						else {
							this.$logs({apiUrl: '获取预览地址',data:data,result:result.data},'error')
							if (this.liveState == false || this.count == 10) {
								if(page.length ==2){
									uni.showModal({
										title: '提示',
										content: getApp().globalData.errCodeMsg.RetCodeMsg[Ret] || result.data.data.retMsg,
										showCancel: false,
										success: (res) => {
											if (res.confirm) {
												this.count == 0
											}
										}
									});
								}
							}
						}
					}else if(result.data.code == 4103){
						this.tryCount ++
						if(this.tryCount == 1){
							this.livestream()
						}else{
							if(page.length ==2){
								uni.showToast({
									title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
									icon:'none'
								})
							}
						}
						this.$logs({apiUrl: '获取预览地址',sn:this.device.deviceNo,data:data,result:result.data},'error')
					}else if(result.data.code == 4105 || result.data.code == 1101 || result.data.code == 1102 || result.data.code == 1103 || result.data.code == 1105 || result.data.code == 1056 || result.data.code == 1061){
						this.tryCount ++
						if(this.tryCount == 1){
							this.livestream()
						}else{
							if(page.length ==2){
								uni.showToast({
									title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
									icon:'none'
								})
							}
						}
						this.$logs({apiUrl: '获取预览地址',sn:this.device.deviceNo,data:data,result:result.data},'error')
					}
					//设备正在休眠
					else if (result.data.code == 4120) {
						this.isShowPlayBtn = true
						let constant = getApp().globalData.constant;
						let lexinLOCK5 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK5;
						let lexinLOCK6 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK6;
						let lexinLOCK7 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7;
						let lexinLOCK12 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK12;
						let lexinLOCK13 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK13;
						if(this.device.parentPid == lexinLOCK5 || this.device.parentPid == lexinLOCK6 ||this.device.parentPid == lexinLOCK7 ||this.device.parentPid == lexinLOCK12 ||this.device.parentPid == lexinLOCK13){
							if(page[page.length - 1].$page.fullPath.includes('live-lexin') || page[page.length - 1].$page.fullPath.includes('live1')){
								uni.showModal({
									content:'设备已进入深度休眠状态，请手动唤醒后继续访问设备',
									showCancel:false,
									confirmColor:'#FF0025',
									confirmText:'确定',
									success: (res) => {
										this.backAction()
									}
								})
							}
						}else{
							// uni.showToast({
							// 	title:'设备已进入浅度休眠状态',
							// 	icon:'none'
							// })
						}
						this.$logs({apiUrl: '获取预览地址4120',sn:this.device.deviceNo,data:data,result:result.data},'error')
							
					}else if(result.data.code == 1063 || result.data.code == 1107){
						this.tryTokenCount ++
						if(this.tryTokenCount < 4){
							this.getAdminToken()
						}else{
							if(page.length ==2){
								uni.showToast({
									title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
									icon:"none"
								})
							}
						}
						this.$logs({apiUrl: '获取预览地址1063||1107',sn:this.device.deviceNo,data:data,result:result.data},'error')
						
					}else{
						if(page.length ==2){
							uni.showToast({
								title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
								icon:'none'
							})
						}
						this.$logs({apiUrl: '获取预览地址',sn:this.device.deviceNo,data:data,result:result.data},'error')
					}
				},false,false);
			},
			// 获取对讲地址
			getTalkBackUrl(callback,type,isWebrtc = false) {
				let token = this.device.token;
				let data = {
					mediaType: isWebrtc? 'webrtc' : 'rtmp',
					channel: '0',
					audioCode: 'acc',
					username: this.device.devUserName,
					password: this.device.devPassWord,
					userToken: uni.getStorageSync('accessToken'),
					appKey: getApp().globalData.api.appKey,
					// forceIp:'122.9.143.195',
					encryptType: 'DISABLE',
				};
				if (this.device.adminToken) {
					data.authentication = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				let reqTime = this.getCurrentTime()
				getApp().globalData.api.talkbackUrl(data, token, (result) => {
					// console.log('获取设备对讲地址:', result.data); // 渲染层网络层错误
					let time1 = this.getCurrentTime()
					let page = getCurrentPages()
					let isLivePage = page[page.length - 1].$page.fullPath.includes('door-lock/live1') || page[page.length - 1].$page.fullPath.includes('door-lock/live-lexin')
					// this.$logs({reqTime:reqTime,resTime:time1,apiUrl: '获取对讲地址',sn:this.device.deviceNo,data:data,result:result.data,envVersion:__wxConfig.envVersion})
					
					if(result.data.code == 2000){
						let Ret = result.data.data.Ret
						if (Ret === 100 || Ret === 104) {
							this.$logs({apiUrl: '获取对讲地址成功',sn:this.device.deviceNo,data:data,result:result.data})
							this.talkUrl = result.data.data.url
							// this.talkUrl = 'rtmp://gwm-000-cn-0603.bcloud365.net:1935/f6b31de12e033247/726475900'
							if (typeof callback === 'function') {
								callback(this.talkUrl)
							}
							this.tryTalkTokenCount = 0
							this.tryTalkOfflineCount = 0
							this.tryTalkWakeUpCount = 0
							this.tryTalkTokenErrCount = 0
							this.tryTalkUnnormalCount = 0
							if(this.isLogout){
								uni.$emit('getTalkUrl', {
									deviceNo: this.device.deviceNo,
									token:this.device.token,
									stream: this.stream,
									PassWord: this.device.devPassWord,
									UserName: this.device.devUserName,
									encryptType: 'DISABLE',
									authentication: this.device.adminToken,
									isLogout:this.isLogout
								})
							}
						}else if(Ret === 108){
							// 超时
							this.tryTalkOfflineCount ++
							if(this.tryTalkOfflineCount < 3){
								this.getTalkBackUrl()
							}
						}else if(Ret === 137){
							if(this.tryTalkTokenCount == 1){
								this.getAdminToken()
							}else if(this.tryTalkTokenCount == 2){
								setTimeout(()=>{
									this.getAdminToken()
								},5000)
							}else if(this.tryTalkTokenCount == 3){
								setTimeout(()=>{
									this.getAdminToken()
								},15000)
							}
						}
						else {
							console.log('对讲路由',page,page.length);
							this.$logs({apiUrl: '获取对讲地址',sn:this.device.deviceNo,data:data,result:result.data},'error')
							if(isLivePage){
								// || this.envVersion!='release'
								if ((typeof callback === 'function' && type == 1) || this.envVersion!='release') {
									uni.showToast({
										title:getApp().globalData.errCodeMsg.RetCodeMsg[Ret] || result.data.data.RetMsg,
										icon:'none'
									})
								}
							}
						}
					}
					// 设备不在线4101
					else if(result.data.code == 4101){
						this.tryTalkOfflineCount ++
						if(this.tryTalkOfflineCount == 1){
							this.getTalkBackUrl()
						}else{
							if(isLivePage){
								if ((typeof callback === 'function' && type == 1) || this.envVersion!='release') {
									uni.showToast({
										title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
										icon:"none"
									})
								}
							}
						}
						this.$logs({apiUrl: '获取对讲地址4101',sn:this.device.deviceNo,data:data,result:result.data},'error')
					}
					// 低功耗设备唤醒失败4103
					else if(result.data.code == 4103){
						this.tryTalkWakeUpCount ++
						if(this.tryTalkWakeUpCount == 1){
							this.getTalkBackUrl()
						}else{
							if(isLivePage){
								if ((typeof callback === 'function' && type == 1) || this.envVersion!='release' ) {
									uni.showToast({
										title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
										icon:"none"
									})
								}
							}
						}
						this.$logs({apiUrl:'获取对讲地址4103',sn:this.device.deviceNo,data:data,result:result.data},'error')
					}else if(result.data.code == 1063 || result.data.code == 1107){
						this.tryTalkTokenErrCount ++
						if(this.tryTalkTokenErrCount<4){
							this.getAdminToken('talk')
						}else{
							this.isPush = false
							this.talkIcon = this.talkStausIcon.off[this.pageKey]
							if(isLivePage){
								if((typeof callback === 'function' && type == 1) || this.envVersion!='release' ){
									if(result.data.code == 1063){
										uni.showToast({
											title:result.data.code+getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
											icon:'none'
										})
									} 
								}
								if(result.data.code == 1107 && (typeof callback === 'function' && type == 1)){
									uni.showModal({
										content:'有其他用户正在使用对讲功能，请稍后再试',
										showCancel:false,
										success: (res) => {
											
										}
									})
								}
							}
						}
						this.$logs({apiUrl: '获取对讲地址1063',sn:this.device.deviceNo,data:data,result:result.data},'error')
					}else if(result.data.code == 1101 || result.data.code == 1102 || result.data.code == 1103 || result.data.code == 1105 || result.data.code == 1056 || result.data.code == 1061){
						this.tryTalkUnnormalCount++
						if(this.tryTalkUnnormalCount == 1){
							this.getTalkBackUrl()
						}else{
							if(isLivePage){
								if ((typeof callback === 'function' && type == 1)  || this.envVersion!='release') {
									uni.showToast({
										title:result.data.code+getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
										icon:'none'
									})
								}
							}
						}
					}
					else{
						if(isLivePage){
							if ((typeof callback === 'function' && type == 1)  || this.envVersion!='release') {
								uni.showToast({
									title:result.data.code+getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
									icon:'none'
								})
							}
						}
					}
					
				},false,false);
			},
			getTwoWayVideoUrl(){
				console.log('获取双向视频对讲地址')
				let token = this.device.token;
				let width = String(this.pushVideoInfo.videoWidth)||'360'
				let height = String(this.pushVideoInfo.videoHeight)||'640'
				let systemInfo = uni.getSystemInfo()
				if(systemInfo.deviceModel == 'MT2110'){  // onePlus9RT
					width = '270'
					height = '480' 
				}  
				let data = {
					mediaType: 'rtmp',
					channel: '0',
					audioCode: 'acc',
					username: this.device.devUserName,
					password: this.device.devPassWord,
					userToken: uni.getStorageSync('accessToken'),
					appKey: getApp().globalData.api.appKey,
					encryptType: 'DISABLE',
					audioCodePlayer:this.audioCodePlayer,
					audioAccuracyPlayer:String(this.audioAccuracyPlayer),
					videoPlayer:this.videoPlayer,
					widthPlayer:width,
					heightPlayer:height,
					fpsPlayer:String(this.fps),
					audioKHZPlayer:String(this.audioKHZPlayer)
				};
				if (this.device.adminToken) {
					data.authentication = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				let reqTime = this.getCurrentTime()
				getApp().globalData.api.getTwoWayVideoUrl(data, token, (result) => {
					let time1 = this.getCurrentTime()
					let page = getCurrentPages()
					let isLivePage = page[page.length - 1].$page.fullPath.includes('door-lock/live1') || page[page.length - 1].$page.fullPath.includes('door-lock/live-lexin')
					// this.$logs({reqTime:reqTime,resTime:time1,apiUrl: '获取双向视频对讲地址',sn:this.device.deviceNo,data:data,result:result.data,envVersion:__wxConfig.envVersion})
					if(result.data.code == 2000){
						let Ret = result.data.data.Ret
						if (Ret === 100 || Ret === 104) {
							this.$logs({apiUrl: '获取双向视频对讲地址',sn:this.device.deviceNo,data:data,result:result.data})
							this.twoWayVideoUrl = result.data.data.url//+'?widthPlayer=360&heightPlayer=640'
							console.log('this.twoWayVideoUrl==',this.twoWayVideoUrl);
							// this.operateDeviceAvDecode('Start')
							if (typeof callback === 'function') {
								callback(this.twoWayVideoUrl)
							}
							this.pushVideoContext.start()
							this.tryTalkTokenCount = 0
							this.tryTalkOfflineCount = 0
							this.tryTalkWakeUpCount = 0
							this.tryTalkTokenErrCount = 0
							this.tryTalkUnnormalCount = 0
							if(this.isLogout){
								
							}
						}else if(Ret === 108){
							// 超时
							this.tryTalkOfflineCount ++
							if(this.tryTalkOfflineCount < 3){
								this.getTwoWayVideoUrl()
							}
						}else if(Ret === 137){
							if(this.tryTalkTokenCount == 1){
								this.getAdminToken()
							}else if(this.tryTalkTokenCount == 2){
								setTimeout(()=>{
									this.getAdminToken()
								},5000)
							}else if(this.tryTalkTokenCount == 3){
								setTimeout(()=>{
									this.getAdminToken()
								},15000)
							}
						}else if(Ret === -9971){
							this.talkStatus = true
							// uni.showToast({
							// 	title:'当前对讲已被其他人占用',
							// 	icon:'none',
							// 	duration:1500,
							// 	success:()=>{
							// 		setTimeout(()=>{
							// 			this.backAction()
							// 		},1500)
							// 	}
							// })
						} else {
							this.$logs({apiUrl: '获取双向视频对讲地址',sn:this.device.deviceNo,data:data,result:result.data},'error')
							if(isLivePage){
								if ((typeof callback === 'function' && type == 1) || this.envVersion!='release') {
									uni.showToast({
										title:getApp().globalData.errCodeMsg.RetCodeMsg[Ret] || result.data.data.RetMsg,
										icon:'none'
									})
								}
							}
						}
					}else if(result.data.code == 1061){
						this.tryTalkOfflineCount ++
						if(this.tryTalkOfflineCount < 3){
							this.getTwoWayVideoUrl()
						}
					}else if(result.data.code == 1109){
						this.talkStatus = true
					}
				},false,false)
			},
			//设备暂停、恢复解码
			operateDeviceAvDecode(action) {
				let data = {
					Name: "AVTalk",
					AVTalk: {
						Action: action,
						ProType: 0,
						Channel:0,
						Video: {
							Enc: this.videoPlayer || "H265",
							W: this.videoWidth || 360,
							H: this.videoHeight || 640,
							FPS:this.fps
						},
						Audio: {
							Enc: this.audioCodePlayer || "G711a",
							SB: this.audioAccuracyPlayer || 16,
							SR:this.audioKHZPlayer || 8000
						}
					}
				}
				if(action == 'Call'){
					data = {
						Name : "AVTalk",
						AVTalk: {
							Action:action,
						}
					}
				}
				let token = this.device.token
				getApp().globalData.api.avDecode(data,token, (result) => {
					console.log('设备解码===', result);
					if (result.data.code == 2000) {
						let res = result.data.data
						let ret = res.Ret
						let content = action=='VDResume'?'恢复解码成功':action == 'VDPause'?'暂停解码成功':''
						if(ret == 100){
							// uni.showToast({
							// 	title:content,
							// 	icon:'none'
							// })
						} else if(ret === 503) {
							this.talkStatus = true
						}else{
							uni.showToast({
								title:getApp().globalData.errCodeMsg.RetCodeMsg[ret] || res.RetMsg,
								icon:'none'
							})
						}
					}else if(result.data.code != 4118 && result.data.code != 4100){
						uni.showToast({
							title:getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result.data.msg,
							icon:'none'
						})
					}
				}, false, false)
			},
			// 获取设备最新的adminToken
			getAdminToken(type){
				let data = {
					deviceNo:this.device.deviceNo,
					isLatest:true
				}
				getApp().globalData.api.getDeviceTokenLocal(data, (result) => {
					this.device.adminToken = result.adminToken
					if(type == 'talk'){
						this.getTalkBackUrl()
					}else{
						this.livestream()
					}
				});
			},
			// 停止设备码流
			closeLivestream(stream,callback) {
				const token = this.device.token;
				const data = {
					channel: '0',
					stream: stream||this.stream,
					PassWord: this.device.devPassWord,
					UserName: this.device.devUserName,
					encryptType: 'DISABLE',
					authentication: this.device.adminToken
				};
				getApp().globalData.api.closeLivestream(data, token, (result) => {
					console.log('停止设备码流:', result);
					this.isLoginSuccess = false
					if (typeof callback === 'function') {
						callback();
					}
				});
			},

			// 一直请求直到请求成功（处理：渲染层网络层错误）
			keepRequestUntillRight(url) {
				console.log('=====一直请求直到请求成功=======');
				uni.request({
					method: 'GET',
					url,
					success: (res) => {
						if (res.statusCode == 200) {
							this.url = url
							this.isLoading = false
						} else if (res.statusCode == 400) {
							uni.showModal({
								title: '提示',
								content: res.data,
								showCancel: false
							});
						} else {
							setTimeout(() => {
								this.keepRequestUntillRight(url);
							}, 1000);
						}
					},
					fail: (err) => {
						console.log('error:', err);
					}
				});
			},
			//获取云服务状态
			reqCaps() {
				const data = {
					sn: this.device.deviceNo,
					caps: ['xmc.css']
				};
				getApp().globalData.api.reqCaps(data, (result) => {
					console.log('云服务:', result);
					let time = Math.floor(new Date().getTime() / 1000);
					let caps = result.caps;
					let text = '';
					let flag = false;

					if (!caps['xmc.css.vid.support']) {
						// 不支持的情况下不要显示出来
						text = '不支持';
						flag = false;
					} else if (!caps['xmc.css.vid.enable']) {
						text = '未开通';
						flag = true;
					} else if (caps['xmc.css.vid.expirationtime'] < time) {
						text = '已过期';
						flag = true;
					} else {
						text = '';
						flag = true;
					}
					this.isCloud = flag
					this.cloudText = text
					console.log(this.isCloud);
				});
			},
			//获取当前时间
			getCurrentTime(){
				let time = new Date()
				let time1 = time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()+':'+time.getMilliseconds()
				return time1
			},
			/** ======================================================== video回调 ================================================================== */
			// 显示隐藏控条bar
			bindtap() {
				console.log('binftap');
				this.isShowBar = !this.isShowBar
				if (!this.isShowBar) {
					this.isShowHD = false
				}

			},

			// 当开始/继续播放时触发play事件
			bindplay(ev) {
				console.log('当开始/继续播放时触发play事件:', ev);
			},

			// 当暂停播放时触发 pause 事件
			bindpause(ev) {
				console.log('当暂停播放时触发 pause 事件:', ev);
			},

			// 当播放到末尾时触发 ended 事件
			bindended(ev) {
				console.log('当暂停播放时触发 pause 事件:', ev);
			},

			// 播放进度变化时触发
			bindtimeupdate(ev) {
				// console.log('播放进度变化时触发:',ev);
				if (this.isLoading) {
					this.isLoading = false
				}
			},

			// 视频进入和退出全屏时触发
			bindfullscreenchange(ev) {
				console.log('视频进入和退出全屏时触发:', ev);
			},

			// 视频出现缓冲时触发
			bindwaiting(ev) {
				console.log('视频出现缓冲时触发:', ev);
				this.isLoading = true
				this.loadingText = '缓冲中...'
			},

			// 视频播放出错时触发
			binderror(ev) {
				console.log('视频播放出错时触发:', ev);
				uni.showModal({
					title: '提示',
					content: '媒体链接已断开,请重试',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							let tokenList = [this.device.token];
							this.getDeviceStatus(tokenList, this.deviceList)
						}
					}

				});
			},

			// 加载进度变化时触发，只支持一段加载
			bindprogress(ev) {
				// console.log('加载进度变化时触发，只支持一段加载:', ev);
			},

			// 视频元数据加载完成时触发
			bindloadedmetadata(ev) {
				console.log('视频元数据加载完成时触发:', ev);
			},

			// 切换 controls 显示隐藏时触发
			bindcontrolstoggle(ev) {
				console.log('切换 controls 显示隐藏时触发:', ev);
			},

			// 播放器进入小窗
			bindenterpictureinpicture(ev) {
				console.log('播放器进入小窗:', ev);
			},

			// 播放器进入小窗
			bindleavepictureinpicture(ev) {
				console.log('播放器退出小窗:', ev);
			},

			// seek 完成时触发
			bindseekcomplete(ev) {
				console.log('seek 完成时触发:', ev);
			},

			/** ================================================== 标高清切换 & 截图 =================================================================== */
			// 标清高清切换
			onBindtapSDFHD() {
				if (this.stream === '1') {
					this.isLoading = true
					this.loadingText = '切换为标清...'
					this.url = ''
					this.streamText = '标清'
					this.streamTextIcon = 'SD'
				} else {
					this.isLoading = true
					this.loadingText = '切换为高清...'
					this.url = ''
					this.streamText = '高清'
					this.streamTextIcon = 'FHD'
				}

				this.closeLivestream(this.stream == '0'?'1':'0',() => {
					// if (this.stream === '0') {
					// 	this.stream = '1'
					// } else {
					// 	this.stream = '0'
					// }
					setTimeout(() => {
						this.livestream();
					}, 3000);
				});
			},

			/**===================================================== 其他 ============================================================================= */
			// 全屏
			onBindtapFullScreen(ev) {
				console.log('全屏：', ev);
				this.videoContext.requestFullScreen();
				this.isFullScreen = true
			},

			// 取消全屏
			onBindtapExitFullScreen(ev) {
				console.log('取消全屏：', ev);
				this.videoContext.exitFullScreen();
				this.isFullScreen = false
			},

			// 云服务
			onBindtapCloud() {
				uni.navigateTo({
					url: `/jvss/pagesDevice/device/device-live/cloud/cloud?device=${JSON.stringify(this.device)}`
				});
			},

			// 云回放
			onBindtapReplay() {
				uni.navigateTo({
					url: `/jvss/pagesDevice/device/device-live/replay/replay?device=${JSON.stringify(this.device)}`
				});
			},

			// 设置
			onBindtapSetting() {
				uni.navigateTo({
					url: `/jvss/pagesDevice/device/device-live/setting/setting?device=${JSON.stringify(this.device)}`
				});
			},

			showOk() {
				this.talkStatus = false
				this.backAction()
			}
		}
	};